﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using PhoneManager.LanguageText;

namespace PhoneManager
{
    public partial class FrmPhoneBook : FrmDefault
    {
        private int QtdSIM = 0;
        private int QtdPhone = 0;
        private string FindLetter = "";
        private string FindText = "";
        private bool ISFirst = false;

        public FrmPhoneBook()
        {
            InitializeComponent();
        }
        public bool ShowSync { get; set; }


        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void BntCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void CalcPages(int IniPage)
        {
            int QtdItens = 0;
            foreach (PhoneBook item in SharedLib.PhonesBook)
            {
                bool ok = true;
                if (FindLetter != "")
                {
                    if (!item.Name.ToUpper().Trim().StartsWith(FindLetter))
                    {
                        ok = false;
                    }
                }
                else if (FindText != "")
                {
                    if (item.Name.ToUpper().IndexOf(FindText) < 0)
                    {
                        ok = false;
                    }
                }
                if (ok)
                {
                    QtdItens++;
                }
            }
            int PageMax;
            if (QtdItens < Properties.Settings.Default.DefaultBookItemsOfPage)
            {
                PageMax = 1;
            }
            else
            {
                PageMax = (int)QtdItens / Properties.Settings.Default.DefaultBookItemsOfPage;
                if ((PageMax * Properties.Settings.Default.DefaultBookItemsOfPage) < QtdItens)
                {
                    PageMax++;
                }
            }
            ISFirst = true;
            if (IniPage > PageMax)
            {
                IniPage = PageMax;
            }
            UpDnPag.Maximum = PageMax;
            UpDnPag.Value = IniPage;
            ISFirst = false;
            UpDnPag.Minimum = 1;
            LblTotPg.Text = ResourcesText.WordOf +  " " + PageMax.ToString();
        }
        private void LoadContacts(bool Calc)
        {
            LoadContacts(Calc, 1);
        }
        private void LoadContacts(bool Calc,int Page)
        {
            if (Calc)
            {
                CalcPages(Page);
            }
            flowLayoutPanel.Controls.Clear();
            QtdPhone = 0;
            QtdSIM = 0;

            int StartItem = ((((int)UpDnPag.Value) - 1) * Properties.Settings.Default.DefaultSyncItemsOfPage) + 1;
            int EndItem = StartItem + Properties.Settings.Default.DefaultSyncItemsOfPage - 1;
            int pos = 0;

            foreach (PhoneBook item in SharedLib.PhonesBook)
            {
                bool ok = true;
                if (FindLetter != "")
                {
                    if (!item.Name.ToUpper().Trim().StartsWith(FindLetter))
                    {
                        ok = false;
                    }
                }
                else if (FindText != "")
                {
                    if (item.Name.ToUpper().IndexOf(FindText) < 0)
                    {
                        ok = false;
                    }
                }
                if (ok)
                {
                    pos++;
                    if (pos < StartItem)
                    {
                        ok = false;
                    }
                }
                if (ok)
                {
                    if (pos > EndItem)
                    {
                        break;
                    }
                    UCPhoneBook UPB = new UCPhoneBook();
                    UPB.Index = pos;
                    UPB.NameContact = item.Name.Trim();
                    UPB.NumberContact = item.Number.Trim();
                    UPB.PhoneID = item.PhoneIndex;
                    UPB.SIMID = item.SIMIndex;
                    UPB.Encoding = Properties.Settings.Default.DefaultCharSet;
                    UPB.SentToPhone = (item.PhoneIndex != "");
                    UPB.SendToSIM = (item.SIMIndex != "");
                    UPB.RestoreIndex = item.RestoreIndex;
                    if (UPB.RestoreIndex > 0)
                    {
                        UPB.RedColor = true;
                    }
                    UPB.EventUCPhoneBook += new UCPhoneBook.UCPhoneBookEventHandler(UPB_EventUCPhoneBook);
                    flowLayoutPanel.Controls.Add(UPB);
                }
            }
            FindLetter = "";
            FindText = "";
            foreach (PhoneBook item in SharedLib.PhonesBook)
            {
                if (item.SIMIndex != "")
                {
                    QtdSIM++;
                }
                if (item.PhoneIndex != "")
                {
                    QtdPhone++;
                }
            }
            string txt = QtdPhone.ToString() + "/" + SharedLib.PhoneBookMEMRanger.Max.ToString();
            LblQtdPhone.Text = txt;
            txt = QtdSIM.ToString() + "/" + SharedLib.PhoneBookSIMRanger.Max.ToString();
            LblQtdSIM.Text = txt;
        }
        private void FrmPhoneBook_Shown(object sender, EventArgs e)
        {
            Cursor oldCur = SharedLib.MainForm.Cursor;
            SharedLib.MainForm.Cursor = Cursors.WaitCursor;
            LoadContacts(true);
            SharedLib.MainForm.Cursor = oldCur;
            if (ShowSync)
            {
                ShowSync = false;
                BntSync.PerformClick();
            }
        }

        private void UPB_EventUCPhoneBook(object sender, UCPhoneBookEventArgs e)
        {
            if (e.CheckedPhone != 0)
            {
                if (QtdPhone + e.CheckedPhone > SharedLib.PhoneBookMEMRanger.Max)
                {
                    SharedLib.MsgAlert(ResourcesText.MsgErrMaxMemoryPhone);
                    ((UCPhoneBook)sender).SentToPhone = false;
                }
                else
                {
                    QtdPhone += e.CheckedPhone;
                }
            }
            else if (e.CheckedSim != 0)
            {
                if (QtdSIM + e.CheckedSim > SharedLib.PhoneBookSIMRanger.Max)
                {
                    SharedLib.MsgAlert(ResourcesText.MsgErrMaxMemorySIM);
                    ((UCPhoneBook)sender).SendToSIM = false;
                }
                else
                {
                    QtdSIM += e.CheckedSim;
                }
            }
            string txt = QtdPhone.ToString() + "/" + SharedLib.PhoneBookMEMRanger.Max.ToString();
            LblQtdPhone.Text = txt;
            txt = QtdSIM.ToString() + "/" + SharedLib.PhoneBookSIMRanger.Max.ToString();
            LblQtdSIM.Text = txt;
        }

        private void PctPesq_Click(object sender, EventArgs e)
        {
            FindText = TxtFind.Text.ToUpper().Trim();
            FindLetter = "";
            LoadContacts(true);
        }

        private void Lnk_Letter_Click(object sender, EventArgs e)
        {
            FindLetter = ((LinkLabel)sender).Text;
            FindText = "";
            TxtFind.Text = "";
            LoadContacts(true);
        }

        private void Lnk_All_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FindLetter = "";
            FindText = "";
            TxtFind.Text = "";
            LoadContacts(true);
        }

        private void UpDnPag_ValueChanged(object sender, EventArgs e)
        {
            if (!ISFirst)
            {
                LoadContacts(false);
            }
        }

        private void BntSync_Click(object sender, EventArgs e)
        {
            for (double i = 0; i < 1; i += 0.1)
            {
                this.Opacity = 1 - i;
                Application.DoEvents();
                Thread.Sleep(40);
            }
            FrmSyncContacts frm = new FrmSyncContacts();
            frm.Owner = this;
            if (SharedLib.GetQtdNotSyncContacts() > 0)
            {
                frm.Filter = FilterTypeEnum.NotSync;
                
            }
            else
            {
                frm.Filter = FilterTypeEnum.LiveGoogle;
            }
            frm.Opacity = 0;
            frm.ShowDialog();
            SharedLib.PhonesBook.Sort(new OrderPhoneBook());
            flowLayoutPanel.Controls.Clear();
            LoadContacts(true, (int)UpDnPag.Value);
            for (double i = 0; i < 1; i += 0.1)
            {
                this.Opacity = i;
                Application.DoEvents();
                Thread.Sleep(40);
            }
        }

        private void LnkUp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            foreach (UCPhoneBook item in flowLayoutPanel.Controls)
            {
                item.ChangeNameContact(item.NameContact.ToUpper());
            }
        }

        private void LnkLW_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            foreach (UCPhoneBook item in flowLayoutPanel.Controls)
            {
                item.ChangeNameContact(item.NameContact.ToLower());
            }
        }

        private void LnkUFL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            foreach (UCPhoneBook item in flowLayoutPanel.Controls)
            {
                string[] param = item.NameContact.Split(' ');
                string name = "";
                foreach (string p in param)
                {
                    if (p.Length > 2)
                    {
                        name += p.Substring(0, 1).ToUpper() + p.Substring(1).ToLower() + " ";
                    }
                    else
                    {
                        if (p.ToLower() == item.NameContact.ToLower())
                        {
                            name += p.ToUpper();
                        }
                        else
                        {
                            name += p.ToLower() + " ";
                        }
                    }
                }
                item.ChangeNameContact(name.Trim());
            }
        }

        private void BntAddPhone_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.3;
            FrmAddPhone Frm = new FrmAddPhone();
            Frm.Owner = this;
            Frm.TopMost = true;
            Frm.ShowDialog();
            flowLayoutPanel.Controls.Clear();
            LoadContacts(true, (int)UpDnPag.Value);
            this.Opacity = 1;
        }

        private void BntSave_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.3;
            this.Cursor = Cursors.WaitCursor;
            SharedLib.StartWaitProcessThread();
            bool IsChange = false;
            bool ErroGSM = false;
            string ErrName = "";
            string ErrNumber = "";
            foreach (UCPhoneBook item in flowLayoutPanel.Controls)
            {
                if (item.IsRemove)
                {
                    if (item.RestoreIndex > 0)
                    {
                        PhoneBook pb = SharedLib.FindPhoneByRestoreID(item.RestoreIndex);
                        if (pb != null)
                        {
                            SharedLib.PhonesBook.Remove(pb);
                            IsChange = true;
                        }
                    }
                    else
                    {
                        if (item.PhoneID != "")
                        {
                            bool ok = SharedLib.ModemGSM.PBookPhoneDelete(item.PhoneID);
                            if (ok)
                            {
                                PhoneBook pb = SharedLib.FindPhoneByID(item.PhoneID, false);
                                if (pb != null)
                                {
                                    SharedLib.PhonesBook.Remove(pb);
                                    IsChange = true;
                                }
                            }
                            else
                            {
                                ErrName = item.NameContact;
                                ErrNumber = item.NumberContact;
                                ErroGSM = true;
                            }
                        }
                        if (item.SIMID != "")
                        {
                            bool ok = SharedLib.ModemGSM.PBookSimDelete(item.SIMID);
                            if (ok)
                            {
                                PhoneBook pb = SharedLib.FindPhoneByID(item.SIMID, true);
                                if (pb != null)
                                {
                                    SharedLib.PhonesBook.Remove(pb);
                                    IsChange = true;
                                }
                            }
                            else
                            {
                                ErrName = item.NameContact;
                                ErrNumber = item.NumberContact;
                                ErroGSM = true;
                            }
                        }
                    }
                }
                else
                {
                    if (item.IsHasChange())
                    {
                        IsChange = true;
                        bool AddP = false;
                        bool AddS = false;
                        if (item.SentToPhone)
                        {
                            if (item.PhoneID != "")
                            {
                                bool ok = SharedLib.ModemGSM.PBookPhoneUpdate(item.PhoneID, item.NameContact, item.NumberContact);
                                if (ok)
                                {
                                    item.RedColor = false;
                                    PhoneBook pb = SharedLib.FindPhoneByID(item.PhoneID, false);
                                    if (pb != null)
                                    {
                                        pb.Name = item.NameContact;
                                        pb.Number = item.NumberContact;
                                    }
                                }
                                else
                                {
                                    ErrName = item.NameContact;
                                    ErrNumber = item.NumberContact;
                                    ErroGSM = true;
                                }
                            }
                            else
                            {
                                AddP = true;
                            }

                        }
                        else
                        {
                            if (item.PhoneID != "")
                            {
                                PhoneBook pb = SharedLib.FindPhoneByID(item.PhoneID, false);
                                bool ok = SharedLib.ModemGSM.PBookPhoneDelete(item.PhoneID);
                                if (!ok)
                                {
                                    ErrName = item.NameContact;
                                    ErrNumber = item.NumberContact;
                                    ErroGSM = true;
                                }
                                else
                                {
                                    pb.PhoneIndex = "";
                                }
                            }
                        }

                        if (item.SendToSIM)
                        {
                            if (item.SIMID != "")
                            {
                                bool ok = SharedLib.ModemGSM.PBookSimUpdate(item.SIMID, item.NameContact, item.NumberContact);
                                if (ok)
                                {
                                    item.RedColor = false;
                                    PhoneBook pb = SharedLib.FindPhoneByID(item.SIMID, true);
                                    if (pb != null)
                                    {
                                        pb.Name = item.NameContact;
                                        pb.Number = item.NumberContact;
                                    }
                                }
                                else
                                {
                                    ErrName = item.NameContact;
                                    ErrNumber = item.NumberContact;
                                    ErroGSM = true;
                                }
                            }
                            else
                            {
                                AddS = true;
                            }
                        }
                        else
                        {
                            if (item.SIMID != "")
                            {
                                PhoneBook pb = SharedLib.FindPhoneByID(item.SIMID,true);
                                bool ok = SharedLib.ModemGSM.PBookSimDelete(item.SIMID);
                                if (!ok)
                                {
                                    ErrName = item.NameContact;
                                    ErrNumber = item.NumberContact;
                                    ErroGSM = true;
                                }
                                else
                                {
                                    pb.SIMIndex = "";
                                }


                            }
                        }
                        int IndexP = -1;
                        int IndexS = -1;
                        if (AddP && AddS)
                        {
                            IndexP = SharedLib.ModemGSM.PBookPhoneInsert(item.NameContact, item.NumberContact);
                            if (IndexP < 0)
                            {
                                ErrName = item.NameContact;
                                ErrNumber = item.NumberContact;
                                ErroGSM = true;
                            }
                            IndexS = SharedLib.ModemGSM.PBookSimInsert(item.NameContact, item.NumberContact);
                            if (IndexS < 0)
                            {
                                ErrName = item.NameContact;
                                ErrNumber = item.NumberContact;
                                ErroGSM = true;
                            }
                        }
                        else if (AddP && !AddS)
                        {
                            IndexP = SharedLib.ModemGSM.PBookPhoneInsert(item.NameContact, item.NumberContact);
                            if (IndexP < 0)
                            {
                                ErrName = item.NameContact;
                                ErrNumber = item.NumberContact;
                                ErroGSM = true;
                            }
                        }
                        else if (!AddP && AddS)
                        {
                            IndexS = SharedLib.ModemGSM.PBookSimInsert(item.NameContact, item.NumberContact);
                            if (IndexS < 0)
                            {
                                ErrName = item.NameContact;
                                ErrNumber = item.NumberContact;
                                ErroGSM = true;
                            }
                        }
                        if ((AddP || AddS) && !ErroGSM)
                        {
                            if (AddP)
                            {
                                PhoneBook pbe = SharedLib.FindPhoneByID(item.SIMID, true);
                                if (pbe != null)
                                {
                                    IndexS = int.Parse(pbe.SIMIndex);
                                }
                            }
                            if (AddS)
                            {
                                PhoneBook pbe = SharedLib.FindPhoneByID(item.PhoneID, false);
                                if (pbe != null)
                                {
                                    IndexP = int.Parse(pbe.SIMIndex);
                                }
                            }
                            item.RedColor = false;
                            PhoneBook pb = new PhoneBook();
                            pb.Name = item.NameContact;
                            pb.Number = item.NumberContact;
                            pb.PhoneIndex = IndexP == -1 ? "" : IndexP.ToString();
                            pb.SIMIndex = IndexS == -1 ? "" : IndexS.ToString();
                            PhoneBook pbm = SharedLib.FindPhoneByRestoreID(item.RestoreIndex);
                            if (pbm != null)
                            {
                                pbm.Name = pb.Name;
                                pbm.Number = pb.Number;
                                pbm.PhoneIndex = pb.PhoneIndex;
                                pbm.SIMIndex = pb.SIMIndex;
                                pbm.RestoreIndex = 0;
                            }
                            else
                            {
                                if (AddS && AddP)
                                {
                                    SharedLib.PhonesBook.Add(pb);
                                }
                                else
                                {
                                    PhoneBook pbe = SharedLib.FindPhoneByID(IndexS.ToString(), true);
                                    if (pbe != null)
                                    {
                                        pbe.PhoneIndex = IndexP.ToString();
                                    }
                                    else
                                    {
                                        pbe = SharedLib.FindPhoneByID(IndexP.ToString(), false);
                                        if (pbe != null)
                                        {
                                            pbe.SIMIndex = IndexS.ToString();
                                        }
                                    }
                                }
                           }
                        }
                    }
                }
                if (ErroGSM)
                {
                    break;
                }
            }
            SharedLib.EndWaitProcessThread();
            this.Cursor = Cursors.Default;
            if (ErroGSM)
            {
                string Msg = ResourcesText.ErrSaveAction + "\n";
                Msg += ResourcesText.WordName + " : " + ErrName + "\n";
                Msg += ResourcesText.WordNumber + " : " + ErrNumber + "\n";
                SharedLib.MsgAlert(Msg);
                SharedLib.PhonesBook.Sort(new OrderPhoneBook());
                flowLayoutPanel.Controls.Clear();
                LoadContacts(true, (int)UpDnPag.Value);
            }
            else if (IsChange)
            {
                SharedLib.MsgAlert(ResourcesText.SaveOkPhonebook);
                SharedLib.PhonesBook.Sort(new OrderPhoneBook());
                flowLayoutPanel.Controls.Clear();
                LoadContacts(true, (int)UpDnPag.Value);
            }
            else
            {
                SharedLib.MsgAlert(ResourcesText.NoChangeAct);
            }
            this.Opacity = 1.0;
        }
    }
}
